package com.echo.week.web;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import okhttp3.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author echo
 * @Description
 * @Date 2023/10/21.
 * @Version 1.0
 */
@RestController
public class DemoController {

    @RequestMapping("/hello")
    public String hello(@RequestParam(value = "id") Long id, @RequestBody User params) {
        if (id != 1) {
            return null;
        }
        System.out.println(params.toString());
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        List<User> users = new ArrayList<>();
        users.add(new User("张三", 1, "男"));
        users.add(new User("李四", 2, "男"));
        users.add(new User("王五", 3, "女"));

        return JSON.toJSONString(users);
    }

    @RequestMapping("/hello1")
    public String hello1(@RequestParam(value = "id") Long id) {
        if (id != 2) {
            return null;
        }
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        List<User> users = new ArrayList<>();
        users.add(new User("张三1", 11, "男"));
        users.add(new User("李四1", 21, "男"));
        users.add(new User("王五1", 31, "女"));

        return JSON.toJSONString(users);
    }

    @RequestMapping("/hello2")
    public String hello2(@RequestParam(value = "id") Long id) {
        if (id != 3) {
            return null;
        }
        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        List<User> users = new ArrayList<>();
        users.add(new User("张三2", 12, "男"));
        users.add(new User("李四2", 22, "男"));
        users.add(new User("王五2", 32, "女"));

        return JSON.toJSONString(users);
    }

    @RequestMapping("/demo")
    public String demo() throws InterruptedException, IOException {

        OkHttpClient client = new OkHttpClient();
        final CountDownLatch countDownLatch = new CountDownLatch(3);
        // 使用ConcurrentLinkedQueue 存储每个请求的响应结果，ConcurrentLinkedQueue 是一个线程安全的
        final ConcurrentLinkedQueue<Response> responses = new ConcurrentLinkedQueue<>();
        ExecutorService executor = Executors.newFixedThreadPool(10);
        long start = System.currentTimeMillis();
        for (int i = 1; i <= urls.size(); i++) {
            String url = urls.get(i - 1);
            int finalI = i;
            executor.submit(() -> {
                //构建请求中需要的请求参数 id 通过 RequestParam获取
                HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
                urlBuilder.addQueryParameter("id", String.valueOf(finalI));
                String newUrl = urlBuilder.build().toString();
                // 表单提交
//                FormBody formBody = new FormBody.Builder().add("id", String.valueOf(finalI)).build();
//                Request request = new Request.Builder().url(newUrl).post(formBody).build();
                // 构建参数，通过@RequestBody取出参数
                User user = new User("1", 2, "男");
                okhttp3.RequestBody requestBody = okhttp3.RequestBody.create(MediaType.parse("application/json; charset=utf-8"),JSON.toJSONString(user));
                Request request = new Request.Builder().url(newUrl).post(requestBody).build();
                try {
                    Response response = client.newCall(request).execute();
                    if (!response.isSuccessful()) {
                        // 可以在单独记录下，然后做异常处理
                        throw new IOException("请求失败：" + response);
                    } else {
                        responses.add(response);
                    }

                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    // 执行一个请求进行一次计数
                    countDownLatch.countDown();
                }
            });
        }

        //等待countDownlatch 计数门闩归零即所有线程请求完成，然后唤醒线程，但是会设置一个最长等待时长 10s
        boolean await = countDownLatch.await(10, TimeUnit.SECONDS);
        executor.shutdown();
        long end = System.currentTimeMillis();
        System.out.println("http的整个请求时间为：" + DateUtil.formatBetween(end - start));
        Map<String,  List<User>> res = new HashMap<>();
        if (!responses.isEmpty()) {
            int i = 0;
            for (Response response : responses) {
                String url = response.request().url().toString();
                String string = response.body().string();
                List<User> users = JSON.parseArray(string, User.class);
                res.put(url,users);
            }
        } else {
            System.out.println("无响应结果！");
        }

        System.out.println(res);
        return "demo";
    }

    private static final List<String> urls = new ArrayList<>();

    static {
        urls.add("http://localhost:8080/hello");
        urls.add("http://localhost:8080/hello1");
        urls.add("http://localhost:8080/hello2");
    }


    public static class User {
        private String name;

        private Integer age;

        private String sex;

        public User(String name, Integer age, String sex) {
            this.name = name;
            this.age = age;
            this.sex = sex;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    ", sex='" + sex + '\'' +
                    '}';
        }
    }
    public static void main(String[] args) {
        System.out.println("1".equals(null));
    }
}
